package controller;

import dao.SearchDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import service.ExcelService;
import util.CheckImportUtil;
import util.ImportExcel;
import util.ReturnResultUtil;
import view.ImportReturnView;
import view.ImportView;
import view.QueryView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * Created by gable on 2018/5/21.
 */
@Controller
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    CheckImportUtil checkImportUtil;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private SearchDao searchDao;


    /**
     * @Author: 杨青桦
     * @Description: excel导入
     * @Date: 2018/5/23 10:48
     * @param request
     * @param queryView
     * @return
     */
    @RequestMapping(value = "import",method = RequestMethod.POST)
    @ResponseBody
    public ReturnResultUtil importExcel(HttpServletRequest request, QueryView queryView){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile mfile = multipartRequest.getFile("file");
        String rootPath = request.getSession().getServletContext().getRealPath("\\upload\\");
        try{
            if(queryView.getYear() == null || queryView.getMonth() == null ||
                    queryView.getYear() > LocalDate.now().getYear() || queryView.getYear() < 2000 ||
                    queryView.getMonth() > 12 || queryView.getMonth() < 1 ){
                return new ReturnResultUtil(0,"时间参数错误");
            }
            Long ym = new Date().getTime();
            if(!mfile.isEmpty()){
                String suffix = mfile.getOriginalFilename().substring(mfile.getOriginalFilename().lastIndexOf(".")+1);
                if(!suffix.equals("xlsx")){
                    return new ReturnResultUtil(0,"上传的文件格式有误，请上传后缀名为xlsx的excel文件!");
                }
                File rootFile = new File(rootPath);
                if (rootFile.exists()) {
                    rootFile.delete();
                    rootFile.mkdirs();
                } else {
                    rootFile.mkdirs();
                }
                //拼接文件名
                String filePath = queryView.getYear() + "_" + queryView.getMonth()+ "_" + ym + "." + suffix;
                File file = new File(rootPath + "\\" + filePath);
                mfile.transferTo(file);
                //解析excel
                List<Object> list = ImportExcel.excelRead(file,CheckImportUtil.properties, ImportView.class);
                CheckImportUtil.resultMap.put(queryView.getYear() + "" + queryView.getMonth(),list );
                //校验数据正确性
                ImportReturnView importReturnView = checkImportUtil.checkImport((List<ImportView>)CheckImportUtil.resultMap.get(queryView.getYear() + "" + queryView.getMonth()));
                if(!importReturnView.getBool()){
                    return new ReturnResultUtil(0,"数据错误",importReturnView);
                }
                //校验数据是否重复
                int count = searchDao.checkRepeatImport(queryView);
                if(count > 0){
                    return new ReturnResultUtil(0,"已存在"+queryView.getYear()+"年"+queryView.getMonth()+"月的数据");
                }
                return excelService.save(queryView,(List<ImportView>)CheckImportUtil.resultMap.get(queryView.getYear() + "" + queryView.getMonth()));

            }else{
                return new ReturnResultUtil(0,"请上传文件");
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(0,"上传文件出现异常");
    }


    /**
     * @Author: 杨青桦
     * @Description:  保存数据
     * @Date: 2018/5/23 10:57
     * @param queryView
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public ReturnResultUtil save(QueryView queryView){
        try {
            if(queryView.getYear() == null || queryView.getMonth() == null ||
                    queryView.getYear() > LocalDate.now().getYear() || queryView.getYear() < 2000 ||
                    queryView.getMonth() > 12 || queryView.getMonth() < 1 ){
                return new ReturnResultUtil(0,"时间参数错误");
            }
            String key = queryView.getYear() + "" + queryView.getMonth();
            //检查是否已存在数据
            int count = searchDao.checkRepeatImport(queryView);
            if(count > 0) {
                excelService.deleteRepeatData(queryView); //删除原先数据
            }
            return excelService.save(queryView,(List<ImportView>)CheckImportUtil.resultMap.get(key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(0, "保存异常");
    }


}
